<?php

namespace App\Http\Middleware;

use App\Exceptions\BusinessException;
use App\Services\ResponseCode;
use Closure;
use Illuminate\Http\Request;

/**
 * Decrypt request body and replace them with decrypted data
 * Class RequestDecrypt
 * @package App\Http\Middleware
 */
class RequestDecrypt
{
    /**
     * Handle an incoming request.
     * @param Request $request
     * @param Closure $next
     * @return mixed
     * @throws BusinessException
     */
    public function handle(Request $request, Closure $next)
    {
        // ignore specific paths
        if(in_array($request->path(), config('api.api_encrypt_exclude_paths'))){
            return $next($request);
        }

        $data = $request->input();

        $isEncrypted = key_exists('encrypted', $data);

        if (config('api.api_encrypt_enable') === true && !$isEncrypted) {
            throw new BusinessException('illegal request content!', ResponseCode::ILLEGAL_REQUEST_CONTENT);
        }

        if ($isEncrypted) {
            $decrypted = json_decode(openssl_decrypt($data['encrypted'], config('api.api_encrypt_algo'), config('api.api_encrypt_passphrase'), 0, config('api.api_encrypt_iv')), true);

            if($decrypted === null){
                throw new BusinessException('invalid encrypt string!', ResponseCode::ILLEGAL_ENCRYPT_STRING);
            }

            // replace request body content with decrypted data
            $request->replace($decrypted);
        }

        return $next($request);
    }
}
